<?php
class ZskxdswModel
{
	private $prefix = 'zsk_browser'; 
    private $table;//表全名
    private $tab;//表缩写名  
	private $sql;//最后一个sql   
	private $wherestr=""; 
	function __construct($name){  
			$this->tab=$this->prefix."_".$name;
			$this->table=" ".tablename($this->prefix."_".$name)." "; 
	}
	function tablename($tab){ 
		$table=tablename($this->prefix."_".$tab); 
		return $table;
	} 
	function where($str=""){
		$this->wherestr=$str; 
		return $this;
	}  
	function lastSql(){
		return $this->sql;
	}    
	function get($field="*"){
		$tb=$this->table;
		$this->limitstr="1";
		$sql =  $this->__replace( "SELECT $field FROM $tb");
		$this->sql=$sql;
		$res = pdo_fetch($sql) ; 
		return $res; 
	} 
	function save($data){
		$tb=$this->table;
		$set ="";
		foreach ($data as $key => $val) {
			$set.="`$key`='".$val."',";
		}
		$set=substr($set,0,strlen($set)-1);
		$sql =  $this->__replace("UPDATE $tb SET $set $where $limit");
		 $this->sql=$sql;    
		 $res=pdo_query($sql); 
		 return $res;  
	}
	//返回插入行id
	function add($data){  
		$tb=$this->table;
		$fields="";
		$values="";
		foreach ($data as $key => $val) {
			$fields.="`".$key."`,";
			$values.='\''.$val.'\',';
		}
		$fields=substr($fields,0,strlen($fields)-1); 
		$values=substr($values,0,strlen($values)-1); 
		$sql =  "INSERT INTO $tb ($fields) VALUES ($values)";
		$this->sql=$sql; 
		$res = pdo_insert($this->tab,$data);  
		return intval(pdo_insertid());  
	} 
	function getall($field="*"){
		$tb=$this->table;
		$sql =  $this->__replace("SELECT $field FROM $tb $where $order ");
		$this->sql=$sql;
		if($this->preQuerySts==true){
			return $this->sql;
		}else{
			$res = pdo_fetchall($sql);
			return $res;
		}
	}
	function __replace($sql){ 
		if(trim($this->wherestr)){
			$isW=stripos($sql," where ");
			if($isW===false){//不匹配where
				if(strlen(trim($this->wherestr))>2){//替换where
						$sql=$sql." WHERE ".$this->wherestr." ";
					} 
			}else{
				if(strlen(trim($this->wherestr))>2){//替换where
						$sql=str_ireplace("WHERE"," WHERE ".$this->wherestr." ", $sql);
				} 
			} 	
		}
		return $sql;
	} 
	 
}